package cfs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import cfs.databean.Employee;
import cfs.formbean.CreateEmployeeFormBean;
import cfs.model.EmployerDAO;
import cfs.model.Model;

public class CreateEmployeeAction extends Action {

	private FormBeanFactory<CreateEmployeeFormBean> formBeanFactory = FormBeanFactory
			.getInstance(CreateEmployeeFormBean.class);

	private EmployerDAO employeeDAO;

	public CreateEmployeeAction(Model model) {
		employeeDAO = model.getEmployerDao();
	}

	public String getName() {
		return "createEmployee.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {
			CreateEmployeeFormBean form = formBeanFactory.create(request);
			request.setAttribute("form", form);

			if (!form.isPresent()) {
				return "CreateEmployee.jsp";
			}

			errors.addAll(form.getValidationErrors());
			if (errors.size() != 0) {
				return "CreateEmployee.jsp";
			}

			Employee user = employeeDAO.lookup(form.getUsername());

			if (user != null) {
				errors.add("This user name already exist");
				return "CreateEmployee.jsp";
			}

			Employee employee = new Employee();

			employee.setFirstname(form.getFirstname());
			employee.setLastname(form.getLastname());
			employee.setPassword(form.getPassword());

			employee.setUsername(form.getUsername());

			employeeDAO.create(employee);

			// Attach (this copy of) the user bean to the session
			HttpSession session = request.getSession(false);
			//session.setAttribute("employee", employee);

			// After successful send to...
			String redirectTo = (String) session.getAttribute("redirectTo");
			if (redirectTo != null)
				return "CreateEmployee.jsp";

			// If redirectTo is null, redirect to the "manage" action
			// String webapp = request.getContextPath();
			else

				request.setAttribute("successStatement", form.getUsername() + " has been created");
				return "Success.jsp";
		} catch (DAOException e) {
			errors.add(e.getMessage());
			return "CreateEmployee.jsp";
		} catch (FormBeanException e) {
			errors.add(e.getMessage());
			return "CreateEmployee.jsp";
		}

	}

}
